package com.dz.risk.controller;

import java.util.Date;
import java.util.List;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dz.risk.common.ResponseVO;
import com.dz.risk.common.exception.RRException;
import com.dz.risk.pojo.QueryParams;
import com.dz.risk.pojo.domain.EarlyWarningDebtListEntity;
import com.dz.risk.service.EarlyWarningDebtListService;
import com.dz.risk.validation.Add;
import com.dz.risk.validation.Update;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;


/**
 * 债卷模块-预警债券名单
 *
 * @author yinpl
 * @email 
 * @date 2021-07-06 17:19:33
 */
@RestController
@RequestMapping("dz-ftsp/stest/earlyWarningDebtList")
@Api(tags = "预警债券名单api", value = "预警债券名单接口")
public class EarlyWarningDebtListController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private EarlyWarningDebtListService earlyWarningDebtListService;

    /**
     * 导入预警债券名单
     *
     */
    @ApiOperation("导入预警债券名单")
    @PostMapping("/upload")
    public ResponseVO upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws Exception {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        // params.setTitleRows(0);
        List<EarlyWarningDebtListEntity> result = ExcelImportUtil.importExcel(multipartFile.getInputStream(),
                EarlyWarningDebtListEntity.class, params);
        System.out.println(result);
        for (int i = 0; i < result.size(); i++) {
            EarlyWarningDebtListEntity earlyWarningDebtListEntity = result.get(i);
            earlyWarningDebtListEntity.setCreatedUser(request.getRemoteUser());
            if (earlyWarningDebtListEntity.getBondCode() == null){
                logger.error("导入参数异常：第"+(i+1)+"行：代码为空");
                return new ResponseVO(201,"第"+(i+1)+"行：代码不能为空");
            }
            if (earlyWarningDebtListEntity.getBondName() == null){
                logger.error("导入参数异常：第"+(i+1)+"行：债券为空");
                return new ResponseVO(201,"第"+(i+1)+"行：债券不能为空");
            }
            if (earlyWarningDebtListEntity.getBondRisk() == null){
                logger.error("导入参数异常：第"+(i+1)+"行：类型为空");
                return new ResponseVO(201,"第"+(i+1)+"行：类型不能为空");
            }
            if (earlyWarningDebtListEntity.getBeginDate() == null){
                logger.error("导入参数异常：第"+(i+1)+"行：开始日为空");
                return new ResponseVO(201,"第"+(i+1)+"行：开始日不能为空");
            }
            if (earlyWarningDebtListEntity.getEndDate() == null){
                logger.error("导入参数异常：第"+(i+1)+"行：结束日为空");
                return new ResponseVO(201,"第"+(i+1)+"行：结束日不能为空");
            }
            if (earlyWarningDebtListEntity.getBeginDate() > earlyWarningDebtListEntity.getEndDate()) {
                return ResponseVO.fail("第"+(i+1)+"行: 开始时间不得大于结束时间");
            }
            List<EarlyWarningDebtListEntity> earlyWarningDebtListEntityList = earlyWarningDebtListService.queryByCode(earlyWarningDebtListEntity.getBondCode());
            for (EarlyWarningDebtListEntity warningDebtListEntity : earlyWarningDebtListEntityList) {
                if (warningDebtListEntity.getBeginDate() != null && warningDebtListEntity.getBeginDate().equals(earlyWarningDebtListEntity.getBeginDate()) &&
                        earlyWarningDebtListEntity.getBondRisk() != null && earlyWarningDebtListEntity.getBondRisk().equals(warningDebtListEntity.getBondRisk())
                ){
                    logger.error("第"+(i+1)+"行：代码为："+earlyWarningDebtListEntity.getBondCode()+"，相同类型："+warningDebtListEntity.getBondRisk()+",在同日期为："+warningDebtListEntity.getBeginDate()+"，已有参数，请更换违约开始日");
                    return new ResponseVO(201,"第"+(i+1)+"行：代码为："+earlyWarningDebtListEntity.getBondCode()+"，相同类型："+warningDebtListEntity.getBondRisk()+",在同日期为："+warningDebtListEntity.getBeginDate()+"，已有参数，请更换违约开始日");
                }
            }
            earlyWarningDebtListEntity.setCreatedTime(new Date());
        }
        //添加集合
        earlyWarningDebtListService.saveBatch(result);
        return ResponseVO.ok("导入成功");
    }

    /**
     * 查询预警债券名单
     *
     */
    @ApiOperation("查询预警债券名单")
    @GetMapping(value = "/query")
    public ResponseVO query( QueryParams queryParams) {
        IPage<EarlyWarningDebtListEntity> iPage =null;
        try {
            iPage = earlyWarningDebtListService.query(queryParams);

        } catch (RRException e) {
            e.printStackTrace();
            logger.error("查询日志信息失败！" + e);
            return new ResponseVO(e.getCode(), e.getMessage());
        }
        return ResponseVO.ok(iPage);

    }

    @ApiOperation("新增违约债券名单")
    @PostMapping("/add")
    public ResponseVO add(@RequestBody @Validated({Add.class}) EarlyWarningDebtListEntity earlyWarningDebtListEntity) {
        return earlyWarningDebtListService.add(earlyWarningDebtListEntity);
    }

    @ApiOperation("根据违约债券Id更新信息 ")
    @PostMapping("/updateById")
    public ResponseVO updateEarlyWarningDebtListEntityById(@RequestBody @Validated({Update.class}) EarlyWarningDebtListEntity earlyWarningDebtListEntity) {
        if (earlyWarningDebtListEntity.getBeginDate() > earlyWarningDebtListEntity.getEndDate()) {
            return ResponseVO.fail("开始时间不得大于结束时间");
        }
        earlyWarningDebtListService.updateEarlyWarningDebtListEntityById(earlyWarningDebtListEntity);
        return ResponseVO.ok();
    }
    /**
     * 根据id删除
     * @param earlyWarningDebtListEntity
     */
    @ApiOperation("根据id删除")
    @PostMapping(value = "/delete")
    public ResponseVO delete(@RequestBody EarlyWarningDebtListEntity earlyWarningDebtListEntity) {
        Assert.notNull(earlyWarningDebtListEntity.getId(), "id is null error");
        try {
            earlyWarningDebtListService.deleteById(earlyWarningDebtListEntity.getId());
        } catch (RRException e) {
            e.printStackTrace();
            return new ResponseVO(e.getCode(), e.getMessage() + e.getCause().getMessage());
        }
        return new ResponseVO(com.dz.risk.common.enums.CodeEnum.SUCCESS);
    }

    /*@RequestMapping("/testImport")
    @ResponseBody
    public ResponseVO importExcel(@RequestParam MultipartFile file){
        try {
            String fileName = file.getOriginalFilename();
            // 获取上传文件的输入流
            InputStream inputStream = file.getInputStream();
            // 调用工具类中方法，读取excel文件中数据
            List<Map<String, Object>> sourceList = ImportExcel.readExcel(fileName, inputStream);

            FileInputStream inp = new FileInputStream((File) file);
            HSSFWorkbook wb = new HSSFWorkbook(inp);
            HSSFSheet sheet = wb.getSheetAt(2); // 获得第三个工作薄(2008工作薄)
// 填充上面的表格,数据需要从数据库查询
            HSSFRow row5 = sheet.getRow(4); // 获得工作薄的第五行
            HSSFCell cell54 = row5.getCell(3);// 获得第五行的第四个单元格
            cell54.setCellValue("测试纳税人名称");// 给单元格赋值
//获得总列数
            int coloumNum=sheet.getRow(0).getPhysicalNumberOfCells();
            int rowNum=sheet.getLastRowNum();//获得总行数
            return ResponseVO.ok("计算成功");

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

            return  new ResponseVO(e.getMessage());
        }

    }*/
}
